const scp = require('scp2')
const colors = require('colors')

const client = new scp.Client()

class WebpackSftp {
  constructor(options = {}) {
    this.options = options
  }
  _upload(srcPath, destPath, client) {
    scp.scp(srcPath, destPath, client,
      function(err,starts) {
        if (err) throw err
        else console.log('Uploading Completed' .green)  
      }
    )
  }

  apply(compiler) {
    const _this = this

    compiler.plugin('done', (compilation) => {
      const remotePath = _this.options.remotePath
      const path = _this.options.path
      const username = _this.options.username
      const host = _this.options.host
      const password = _this.options.password
      const port = _this.options.port || '22'
      const showProcess = _this.options.showProcess

      let startTime
      let endTime

      client.on('connect', function() {
        // console.log('connected');
      });

      client.on('ready', function() {
        let s = new Date()
        startTime = s.getTime()
        console.log('开始自动部署...'.yellow)
      });

      client.on('transfer', function(buf, up, total) {});

      client.on('write', function(p) {
        if (showProcess) {
          console.log(`Uploading  ${p.source}  ======>  ${p.destination}`)
        }
      });

      client.on('end', function() {
        let e = new Date()
        endTime = e.getTime()
        console.log(`End uploading ${e}` .yellow)
      });

      client.on('error', function(err) {
        console.log(`ERROR ${err}` .red)
      });

      client.on('close', function() {
        console.log(`Uploading with SFTP Completed in [ ${ (endTime - startTime) / 1000 } ] seconds!`.green)
        console.log('部署完成...'.yellow)
      });


      let srcPath = path;
      let destPath = username + ':' + password + '@' + host + ':' + port + ':' + remotePath

      _this._upload(srcPath, destPath, client)

    })
  }
}

module.exports = WebpackSftp
